//引入helper
const help = require('./Helper');
//引入雪花算法生成id
const Snowflake = require('./snowflake')
//引入date生成时间
const dateFormat = require('./date')

const multer = require('multer');
const snowflake = require('./snowflake');
const storage = multer.diskStorage({
    //设置文件存储位置
    destination: './uploads',
    filename: function (req, file, cb) {
        //获取图片格式
        let fileType = file.originalname.split('.')
        fileType = fileType[fileType.length - 1]
        //改名
        cb(null, '/' + snowflake() + '.' + fileType)
    }
})

const upload = multer({ storage: storage })

module.exports = function (app) {

    app.use('/admin', loginRouter)

    //登录拦截中间件
    function loginRouter(req, res, next) {
        let token = req.headers.token
        if (req.method.toUpperCase() == 'OPTIONS') {
            next()
            return;
        }
        if (token) {
            help(`select * from session where id = '${token}'`).then(ret => {
                if (ret.length) {
                    let session = ret[0]
                    if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
                        req.session = {
                            userId: session.userId,
                            userName: session.userName,
                        }
                        next()
                    } else {
                        res.status(400).send({ errorMsg: '登录超时' })
                    }
                } else {
                    res.status(400).send({ errorMsg: '当前用户未登录' })
                }
            })
        } else {
            res.status(400).send({ errorMsg: '缺少token,请先进行登录' })
        }
    }

    //文件上传
    app.post('/upload', upload.single('file'), function (req, res, next) {
        res.send(req.file)
    })

    //获取用户信息
    app.post('/login', (req, res) => {
        let userName = req.body.userName
        let passWord = req.body.passWord
        if (userName && passWord) {
            help(`select * from user where userName = '${userName}'`).then(users => {
                if (users.length) {
                    let user = users[0]
                    if (passWord == user.passWord) {
                        let photo = user.photo
                        let token = Snowflake()
                        let date = dateFormat()
                        help(`
                            INSERT INTO session(id,userId,userName,inTime,createTime,platform) 
                            VALUES(${token},'${user._id}','${user.nickName}','${date}','${new Date().getTime()}','admin')
                            `).then(ret => {
                            res.send({
                                img: photo,
                                nickName: user.nickName,
                                _id: user._id,
                                token
                            })
                        })
                    } else {
                        res.send({ errorMsg: '密码错误' })
                    }
                } else {
                    res.send({ errorMsg: '用户不存在' })
                }
            })
        } else {
            res.send({ errorMsg: 'qing输入密码和账号' })
        }
    })

    //退出登录
    app.get('/loginOut', (req, res) => {
        let date = dateFormat()
        help(`
        update session set outTime = '${date}',state = 0 where id = '${req.headers.token}'`).then(ret => {
            res.send({ msg: '退出登录成功' })
        })
    })


    //修改密码
    app.post('/admin/changePassWord', (req, res) => {
        let userId = req.session.userId
        help(`
            select passWord from user where _id = '${userId}'
        `).then(users => {
            let user = users[0]
            if (req.body.passWord == user.passWord) {
                help(`
                update user set passWord = '${req.body.newPassWord}' 
                where _id = '${userId}' 
                `).then(ret => {
                    res.send({ msg: '修改密码成功，请重新登录' })
                })
            } else {
                res.send({ errorMsg: '初始密码错误' })
            }
        })
    })

    //修改上传头像
    app.post('/admin/changeAvatar', (req, res) => {
        let userName = req.body.userName
        let photo = req.body.img
        help(`
        update user set photo = '${photo}'
        where userName = '${userName}'
        `).then(ret => {
            res.send({
                msg: '修改头像成功',
                photo
            })
        })
    })

    //查询首页
    //pageNum  默认为1
    //pageSize 默认为5
    app.get('/admin/get', (req, res) => {
        let type = req.query.type
        let pageSize = req.query.pageSize || 5
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let sqlWhere = `from index_region where type = '${type}' and state = 1`
        if (req.query.title) sqlWhere += ` and title like "%${req.query.title}%"`
        help(`
        select * ${sqlWhere} limit ${pageSize} offset ${offset};
        select count(*) as total ${sqlWhere}
        `).then(ret => {
            res.send(ret ? {
                rows: ret[0],
                total: ret[1][0].total
            } : { errorMsg: '获取数据失败' })
        })
    })

    //新增首页项目
    //img           图片 必填
    //title         标题 必填
    //type          类型 必填   
    //url           跳转地址 非必填
    //stauts        启用状态 非必填 默认为1 
    //description   描述     非必填
    app.post('/admin/add', (req, res) => {
        let img = req.body.img ? req.body.img : ''
        let title = req.body.title ? req.body.title : ''
        let url = req.body.url ? req.body.url : ''
        let type = req.body.type ? req.body.type : ''
        let description = req.body.description ? req.body.description : ''
        let status = req.body.status
        if (status != 1) status = 0
        if (img || type || description || url || title || sort) {
            help(`
            INSERT INTO index_region(img,title,url,status,type,description)
            VALUES('${img}','${title}','${url}',${status},'${type}','${description}')
            `).then(ret => {
                ret.insertId ? res.send({ insertId: ret.insertId }) : res.send({ errorMsg: '新增失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //修改信息
    //indexId   主码     _id  必填
    //img       图片地址 img  非必填
    //path      跳转路径 url  非必填
    //status    启用状态 satus    非必填
    //sort      详情     path     非必填
    //title     标题     title    非必填
    //description 描述            非必填  
    //sort      摘要     sort     非必填 
    app.put('/admin/change', (req, res) => {

        let form = req.body.form ? req.body.form : 'index_region'
        if (req.body.indexId) {
            //需要修改的项
            let updateKey = ['img', 'url', 'status', 'sort', 'title', 'description', 'name', 'imgs', 'brandId', 'type', 'sales', 'props', 'salePrice','originalPrice','skuSpecification']
            let updateValue = []
            for (i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value != undefined) updateValue.push(`${key}='${value}'`)
            }
            help(`update ${form} set ${updateValue.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //删除当前选中项
    //indexId   主码     _id  必填
    app.delete('/admin/delete', (req, res) => {
        let form = req.body.form
        let where
        let id = req.body.indexId
        if (id) {
            // 判断传入参数类型决定是否批量删除
            if (typeof id == 'object') {
                let _id
                for (i = 0; i < id.length; i++) {
                    _id += `${id[i]},`
                }
                where = `where _id in (${id})`
            } else {
                where = `where _id = ${id}`
            }
            ///逻辑删除地址信息
            help(`
            update ${form}
            set state = 0
            ${where}
            `).then(ret => {
                //返回为删除成功的数据
                res.send({
                    affectedRows: ret.affectedRows
                })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //分类列表查询数据
    app.get('/admin/category', (req, res) => {
        help(`
        select * from category
        `).then(ret => {
            res.send(ret)
        })
    })

    //新增分类项目
    app.post('/admin/category', (req, res) => {
        let level = req.body.level
        let id = req.body.id
        let parentId = req.body.parentId
        if (level == 1) {
            id = snowflake()
        } else {
            parentId = id
            id = parentId + "_" + snowflake()
        }
        let img = req.body.img
        let name = req.body.name
        if (name || img) {
            help(`
            INSERT INTO category(img,name,id,parentId,level)
            VALUES('${img}','${name}','${id}','${parentId}',${level})
            `).then(ret => {
                ret.insertId ? res.send({ insertId: ret.insertId }) : res.send({ errorMsg: '新增失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })



    //修改分类信息
    //img      图片地址 img     非必填
    //name     标题     name    非必填
    //level    等级             必填
    app.put('/admin/category', (req, res) => {
        if (req.body.indexId) {
            //需要修改的项
            let updateKey = ['img', 'name', 'parentId']
            let updateValue = []
            for (i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value != undefined) updateValue.push(`${key}='${value}'`)
            }
            help(`update category set ${updateValue.join(',')} where _id = '${req.body.indexId}'`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //商品获取
    //查询商品
    //pageNum  默认为1
    //pageSize 默认为5
    app.get('/admin/goods', (req, res) => {
        let pageSize = req.query.pageSize || 5
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let joinWhere = ''
        let sqlJoinWhere =
        `from product as p
        left join brand as b on p.brandId = b._id`
        if (req.query.title) joinWhere += ` and p.name like "%${req.query.title}%" or b.name like "%${req.query.title}%"`
        let sqlWhere =`from product where state = 1`
        if (req.query.title) sqlWhere += ` and name like "%${req.query.title}%"`
        help(`
        select b.name as brandName,
        p.name,p.brandId,p.imgs,p.description,p.status,p.sales,p._id,p.state
        ${sqlJoinWhere}
        where p.state = 1 ${joinWhere}
        limit ${pageSize} offset ${offset};
        select count(*) as total ${sqlWhere}
        `).then(ret => {
            res.send(ret ? {
                rows: ret[0],
                total: ret[1][0].total
            } : { errorMsg: '标题不存在' })
        })
    })
    //添加分类，添加品牌，删除分类、品牌
    //商品修改 价格、分类、品牌、图片
    app.get('/admin/getBrand', (req, res) => {
        help(`select * from brand`).then(brands => {
            res.send(brands)
        })
    })

    //新增首页项目
    //img           图片 必填
    //title         标题 必填
    //type          类型 必填   
    //url           跳转地址 非必填
    //stauts        启用状态 非必填 默认为1 
    //description   描述     非必填
    app.post('/admin/addProduct', (req, res) => {
        let imgs = req.body.imgs ? req.body.imgs : ''
        let name = req.body.name ? req.body.name : ''
        let brandId = req.body.brandId ? req.body.brandId : ''
        let sales = req.body.sales ? req.body.sales : ''
        let description = req.body.description ? req.body.description : ''
        let status = req.body.status
        if (status != 1) status = 0
        if (imgs || name || brandId || sales || description || status) {
            help(`
            INSERT INTO product(imgs,name,brandId,sales,description,status)
            VALUES('${imgs}','${name}','${brandId}',${sales},'${description}','${status}')
            `).then(ret => {
                ret.insertId ? res.send({ insertId: ret.insertId }) : res.send({ errorMsg: '新增失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //查询所有分类
    app.get('/admin/getCategoryList', (req, res) => {
        help(`
        select c.name,c._id from category as c where level = 2 and state = 1
        `).then(ret => {
            res.send(ret)
        })
    })
    //查询当前商品所属分类
    app.get('/admin/getCategory', (req, res) => {
        let productId = req.query.productId
        help(`
        select p.name as name,c.name as category,c._id as categoryId
        from category_product as cp
        left join product as p
        on p._id = cp.productId
        left join category as c
        on c._id = cp.categoryId
        where cp.productId = ${productId}
        `).then(ret => {
            res.send(ret)
        })
    })
    //修改分类
    //传入productId
    app.post('/admin/changeCategory', (req, res) => {
        let productId = req.body.indexId
        let categoryId = req.body.category
        let insterSql = ';'
        if (categoryId.length) {
            for (let i = 0; i < categoryId.length; i++) {
                insterSql +=
                    `
                INSERT INTO category_product(productId,categoryId) 
                VALUES(${productId},${categoryId[i]});
                `
            }
            help(`
            delete from category_product where productId = ${productId}
            ${insterSql}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            help(`
            delete from category_product where productId = ${productId}`).then(ret => {
                res.send(ret)
            })
        }
    })

    //查询品牌表
    //查询首页
    //pageNum  默认为1
    //pageSize 默认为5
    app.get('/admin/getBrandList', (req, res) => {
        let pageSize = req.query.pageSize || 5
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let sqlWhere = `from brand where state = 1`
        if (req.query.title) sqlWhere += ` and name like "%${req.query.name}%"`
        help(`
        select * ${sqlWhere} limit ${pageSize} offset ${offset};
        select count(*) as total ${sqlWhere}
        `).then(ret => {
            res.send(ret ? {
                rows: ret[0],
                total: ret[1][0].total
            } : { errorMsg: '获取数据失败' })
        })
    })

    //新增品牌
    app.post('/admin/addBrand', (req, res) => {
        let img = req.body.img
        let name = req.body.name
        if (name || img) {
            help(`
            INSERT INTO brand(img,name)
            VALUES('${img}','${name}')
            `).then(ret => {
                ret.insertId ? res.send({ insertId: ret.insertId }) : res.send({ errorMsg: '新增失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //查询sku
    //productId 必传
    //pageNum  默认为1
    //pageSize 默认为5
    app.get('/admin/getSku', (req, res) => {
        if (req.query.productId) {
            let pageSize = req.query.pageSize || 5
            let pageNum = req.query.pageNum || 1
            let offset = (pageNum - 1) * pageSize
            let productId = req.query.productId
            let props = req.query.props ? req.query.props : ''
            let sqlWhere = `
            from sku as s
            left join product as p on s.productId = p._id
            where productId = '${productId}' and s.state = 1
            `
            console.log(sqlWhere)
            if (req.query.props) sqlWhere += ` and props like "%${props}%"`
            help(`
            select s._id,s.props,s.originalPrice,s.salePrice,s.imgs,s.skuSpecification,p.name as productName ${sqlWhere} limit ${pageSize} offset ${offset};
            select count(*) as total ${sqlWhere}
            `).then(ret => {
                res.send(ret ? {
                    rows: ret[0],
                    total: ret[1][0].total
                } : { errorMsg: '获取数据失败' })
            })
        } else {
            res.send({ errorMsg: '请传入productId' })
        }
    })

    //新增sku
    app.post('/admin/addSku', (req, res) => {
        let props = req.body.props
        let salePrice = req.body.salePrice
        let imgs = req.body.imgs
        let skuSpecification = req.body.skuSpecification
        let productId = req.body.productId
        let skuId = snowflake()
        if (props && salePrice && imgs && skuSpecification && productId) {
            help(`
                INSERT INTO sku(props,salePrice,imgs,skuSpecification,productId,skuId)
                VALUES('${props}','${salePrice}','${imgs}','${skuSpecification}','${productId}','${skuId}')
                `).then(ret => {
                ret.insertId ? res.send({ insertId: ret.insertId }) : res.send({ errorMsg: '新增失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
}
